package com.example.service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.service.common.R;
import com.example.service.domain.TUrl;
import com.example.service.dto.AddUrlDto;
import com.example.service.service.TUrlService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.UUID;

@RequestMapping("/s")
@Controller
@RequiredArgsConstructor
@Slf4j
public class ShortUrlController {
    private final TUrlService tUrlService;

    /**
     * 获取短链接
     * @param pat
     */
    @GetMapping("/{pat}")
    public String getUrl(@PathVariable("pat") String pat) {
        LambdaQueryWrapper<TUrl> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUrl::getMapUrl, pat);
        TUrl rawUrl = tUrlService.getOne(wrapper);
        if (Objects.nonNull(rawUrl) && Objects.nonNull(rawUrl.getRawUrl())) {
            return "redirect:" + rawUrl.getRawUrl();
        }
        return "redirect:/404.html";
    }

    /**
     * 添加短链接
     * @param dto
     */
    @PostMapping
    @ResponseBody
    public R addShortUrl(@RequestBody AddUrlDto dto) {
        TUrl tUrl = new TUrl();
        LambdaQueryWrapper<TUrl> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TUrl::getRawUrl, dto.getUrl());
        TUrl isAlreadyExist = tUrlService.getOne(wrapper);
        if (Objects.nonNull(isAlreadyExist)) {
            return R.ok().build();
        }
        String shortUrl;
        while (true) {
            wrapper = new LambdaQueryWrapper<>();
            shortUrl = UUID.randomUUID().toString().substring(0, 5);
            wrapper.eq(TUrl::getMapUrl, shortUrl);
            TUrl one = tUrlService.getOne(wrapper);
            if (Objects.isNull(one)) {
                break;
            }
        }
        tUrl.setRawUrl(dto.getUrl());
        tUrl.setMapUrl(shortUrl);
        boolean save = tUrlService.save(tUrl);
        if (save) {
            return R.ok().build();
        } else {
            return R.fail().build();
        }
    }
}
